package dao;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import application.Factory;
import datacontainers.AllDishes;
import datacontainers.Category;
import datacontainers.Dish;
import datacontainers.Menu;
import datacontainers.Order;
import datacontainers.OrderItem;

public class TextDAO implements DataLoader {

	public Date checkMenu() {
		// TODO Auto-generated method stub
		return null;
	}

	public Menu getMenu() {
		Menu menu = new Menu();

		AllDishes dishes = getAllDishes();

		try {
			File menuFile = new File("menu.txt");
			FileReader menuFR = new FileReader(menuFile);
			BufferedReader menuReader = new BufferedReader(menuFR);

			// load date
			if (menuReader.ready()) {
				long d = Long.parseLong(menuReader.readLine());
				Date date = new Date();
				date.setTime(d);
				menu.setActualDate(date);
			}
			// load dishes
			while (menuReader.ready()) {
				int dishId = Integer.parseInt(menuReader.readLine());

				Dish dish = dishes.findById(dishId);
				if (dish != null) {
					menu.addDish(dish);
				}

			}
			menuReader.close();
		} catch (IOException e) {
			Factory.getLogger().trace("Menu read error!");
			Factory.getLogger().trace(e);
			e.printStackTrace();
		}

		return menu;
	}

	public List<Order> getOrders(final String user) {
		List<Order> orders = new ArrayList<Order>();

		File dir = new File("Orders\\");

		if (dir.isDirectory()) {
			FileFilter filter = new FileFilter() {
				@Override
				public boolean accept(File arg0) {
					return arg0.isFile() && arg0.getName().startsWith(user);
				}

			};

			for (File file : dir.listFiles(filter)) {

			}
		}

		return orders;
	}

	private Order loadOrder(String path) {
		Order order = new Order();
		File orderFile = new File(path);
		List<OrderItem> items = new ArrayList<OrderItem>();
		AllDishes dishes = getAllDishes();

		try {
			FileReader orderR = new FileReader(orderFile);
			BufferedReader orderReader = new BufferedReader(orderR);

			while (orderReader.ready()) {
				OrderItem item = TextParser.parseOI(orderReader.readLine());
				item.setDish(dishes.findById(item.getDish().getId()));
				items.add(item);

			}
			orderReader.close();
			order.setItems(items);
		} catch (IOException e) {
			Factory.getLogger().trace("Order load error");
			Factory.getLogger().trace(e);
			e.printStackTrace();
		}

		return order;
	}

	public void sendOrder(Order order) {
		File orderFile = new File("Orders\\" + order.getUser().getPcName()
		        + String.valueOf(order.getDate().getTime()) + ".lo");
		orderFile.delete();
		try {
			FileWriter orderWr = new FileWriter(orderFile);
			BufferedWriter orderWriter = new BufferedWriter(orderWr);

			for (OrderItem item : order.getItems()) {
				orderWriter.write(String.valueOf(item.getDish().getId()));
				orderWriter.write("\\");
				orderWriter.write(String.valueOf(item.getCount()));
				orderWriter.newLine();
			}
			orderWriter.flush();
			orderWriter.close();

		} catch (IOException e) {
			Factory.getLogger().trace("save order error");
			Factory.getLogger().trace(e);
			e.printStackTrace();
		}
	}

	public void addDish(Dish dish) {
		File dishes = new File("dishes.txt");
		try {
			BufferedWriter dishesWriter = new BufferedWriter(new FileWriter(
			        dishes, true));

			dishesWriter.write(String.valueOf(dish.getId()) + "\\"
			        + dish.getCategory().ordinal() + "\\" + dish.getName()
			        + "\\" + dish.getDescription() + "\\"
			        + String.valueOf(dish.getCost()));
			dishesWriter.newLine();
			dishesWriter.flush();
			dishesWriter.close();
		} catch (IOException e) {
			Factory.getLogger().trace("save dish error");
			Factory.getLogger().trace(e);
		}

	}

	public void saveMenu(Menu menu) {
		File menuFile = new File("menu.txt");
		menuFile.delete();
		try {
			FileWriter menuFW = new FileWriter(menuFile, false);
			BufferedWriter menuWriter = new BufferedWriter(menuFW);

			// saving date
			menuWriter.write(String.valueOf(menu.getActualDate().getTime()));

			// saving dishes id`s
			for (Category cat : Category.values())
				for (Dish t : menu.getCategory(cat)) {
					menuWriter.newLine();
					menuWriter.write(String.valueOf(t.getId()));
				}

			menuWriter.flush();
			menuWriter.close();
		} catch (IOException e) {
			Factory.getLogger().trace("Menu saving error");
			Factory.getLogger().trace(e);
			e.printStackTrace();
		}
	}

	@Override
	public List<Order> getTomorrowOrders() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean checkMenuEditing() {
		File menuFile = new File("menu.txt");

		return !menuFile.canWrite();
	}

	@Override
	public void menuEditingSet(boolean editing) {

		File menuFile = new File("menu.txt");
		menuFile.setWritable(!editing);
	}

	@Override
	public AllDishes getAllDishes() {
		File allDishes = new File("dishes.txt");

		AllDishes dishes = new AllDishes();

		try {
			FileReader allDishesReader = new FileReader(allDishes);
			BufferedReader dishesReader = new BufferedReader(allDishesReader);

			while (dishesReader.ready()) {
				dishes.addDish(TextParser.parseDish(dishesReader.readLine()));
			}

			dishesReader.close();
		} catch (IOException e) {
			Factory.getLogger().trace("Dishes read error!");
			Factory.getLogger().trace(e);
			e.printStackTrace();
		}

		return dishes;
	}

}
